<?php

namespace app\admin\controller;

use app\BaseController;
use think\App;
use think\facade\Db;

/**
 * @author xjw
 * @class:TaskProduct 定时任务=>产品操作
 * @method:product 拉取商品  45分钟执行
 * @method:deal_product 处理商品相关
 * @return  
 */


class Tiktok extends BaseController
{

    protected $model = null;
    protected $app_key = '';
    protected $app_secret = '';
    protected $code = '';
    protected $access_token = '';
    protected $refresh_token = '';
    
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->app_key = '6alcsq6jcuhqn';
        $this->app_secret = '81a48f357bc251c5060bc30835e87f9b00645076';
        $this->code = 'TTP_vPj9vAAAAACNdNowF7BZQY0taHFmVi3ahTTs4LCh-lTjUzjwhAVj5DrXRz-oPU1S4TnFOTNeAbafRORZIj6PVGGoz_Ty48nkQ_jjt6zwzfKcMvZ3tuGW9oQ-oLkV7J6yM6s_ReiWrSLbGOKC1fm69u1C6XEJ0QnkMNjaaxPBIquGtfM-dE5Xrw';
        $this->access_token = 'TTP_pmZXJwAAAACoIxR5KjYUBE-C3RABZ7ivcbhnJHdphWa8wzba68eyO2MZR6WlDIhfiT5cZwlx6X6LaABH4To2lopdSifZp4Xl6lNfneCBhOG4TUxLt0XCrsebp77MtGX5_cft4C1viIjZM29la9kGJBlbwS78eHcOA8qvZ2FIVEeZkTgQf3659g';
        $this->refresh_token = 'TTP_u7utoAAAAADeX3NMzJYpjzW8WSOOH8uAPWSB_HuiMDgpBQpEvRxCIdnZX5feeDy-tzc6U8IdrfA';
    }

    /**
    * 获取验证码
    * @param array params
    */
    public function test()
    {
        $this->code = $this->request->get('code');
        return success('操作成功',$this->code);
    }

    /**
    * 获取token
    * @param array params
    */
    public function token()
    {
        $url = "auth.tiktok-shops.com/api/v2/token/get?app_key=".$this->app_key."&auth_code=".$this->code."&app_secret=".$this->app_secret."&grant_type=authorized_code";
        $data = $this->geturl($url);
        $data = json_decode($data, true);
        halt($data);
    }

    /**
    * 获取token
    * @param array params
    */
    public function refresh_token()
    {
        $url = "https://auth.tiktok-shops.com/api/v2/token/refresh?app_key=".$this->app_key."&app_secret=".$this->app_secret."&refresh_token=".$this->refresh_token."&grant_type=refresh_token";
        $data = $this->geturl($url);
        $data = json_decode($data, true);
        halt($data);
    }
    
    /**
    * 方法详情
    * @param array params
    */
    public function index()
    {
        //去掉sign跟access_token 1.字母顺序重新排列参数键
        // 2.以 {key}{value} 格式连接所有参数
        // 3.附加请求路径
        // 4.如果请求头content_type不是multipart/form-data，则追加body到末尾
        // 5.使用 app_secret 包装在步骤 5 中生成的字符串。
        // 6.使用HMAC-SHA256算法生成签名
        $path = '/authorization/202309/shops';
        $sign = $this->app_secret.''.$path.'app_key'.$this->app_key.'timestamp'.time().''.$this->app_secret;
        $sign = hash_hmac('sha256', $sign,$this->app_secret);
        $url = "https://open-api.tiktokglobalshop.com".$path."?app_key=".$this->app_key."&sign=".$sign."&timestamp=".time();
        // halt($url);
        $data = $this->geturl($url);
        $data = json_decode($data, true);
        halt($data);
    }

    /**
    * 方法详情
    * @param array params
    */
    public function product()
    {
        $sort = array('a','p','s','t');
        sort($sort);
        $shop_cipher = 'TTP_tptbfAAAAACJhOxjslIpiBxiO_L-l9qk';
        $path = '/product/202309/products/search';
        $sign = $this->app_secret.''.$path.'app_key'.$this->app_key.'page_size20shop_cipher'.$shop_cipher.'timestamp'.time().'{"status":"ALL"}'.$this->app_secret;
        $sign = hash_hmac('sha256', $sign,$this->app_secret);
        $url = "https://open-api.tiktokglobalshop.com".$path."?app_key=".$this->app_key."&page_size=20&shop_cipher=".$shop_cipher."&sign=".$sign."&timestamp=".time();
        $data = array();
        $data['status'] = 'ALL';
        $return = $this->posturl($url,$data);
        $return = json_decode($return, true);
        halt($return);
    }
    
    /**
    * 方法详情  GET
    * @param array params
    */
    public function product_categories()
    {
        $shop_cipher = 'TTP_tptbfAAAAACJhOxjslIpiBxiO_L-l9qk';
        $path = '/product/202309/categories';
        $sign = $this->app_secret.''.$path.'app_key'.$this->app_key.'shop_cipher'.$shop_cipher.'timestamp'.time().''.$this->app_secret;
        $sign = hash_hmac('sha256', $sign,$this->app_secret);
        $url = "https://open-api.tiktokglobalshop.com".$path."?app_key=".$this->app_key."&shop_cipher=".$shop_cipher."&sign=".$sign."&timestamp=".time();
        // halt($url);
        $data = $this->geturl($url);
        $data = json_decode($data, true);
        halt($data);
    }

    /**
    * 方法详情  POST
    * @param array params
    */
    public function orderlist()
    {
        $sort = array('a','p','s','t');
        sort($sort);
        $shop_cipher = 'TTP_tptbfAAAAACJhOxjslIpiBxiO_L-l9qk';
        $path = '/order/202309/orders/search';
        $sign = $this->app_secret.''.$path.'app_key'.$this->app_key.'page_size100shop_cipher'.$shop_cipher.'timestamp'.time().'{"order_status":"AWAITING_SHIPMENT"}'.$this->app_secret;
        $sign = hash_hmac('sha256', $sign,$this->app_secret);
        $url = "https://open-api.tiktokglobalshop.com".$path."?app_key=".$this->app_key."&page_size=100&shop_cipher=".$shop_cipher."&sign=".$sign."&timestamp=".time();
        $data = array();
        $data['order_status'] = 'AWAITING_SHIPMENT';
        $return = $this->posturl($url,$data);
        $return = json_decode($return, true);
        // halt($return);
        if(isset($return['data']['orders']) && !empty($return['data']['orders'])){
            $order = $return['data']['orders'][0];
            $hwc = $this->hwc($order);
            halt($hwc);
        }
        halt($return);
    }
    
    /**
    * 方法详情
    * @param array params
    */
    public function hwc($order = array())
    {
        $ParamsJson = array();
        $ParamsJson["Style"] = "1";
        $ParamsJson["ShipperName"] = "";
        $ParamsJson["ShipperAddress"] = "";
        $ParamsJson["ShipperPhone"] = "";
        $ParamsJson["CsRefNo"] = "05141029402";
        $ParamsJson["ConsigneeName"] = "zhang san";
        $ParamsJson["CountryCode"] = "202";
        $ParamsJson["ShipperService"] = "18";
        $ParamsJson["Zipcode"] = "79879";
        $ParamsJson["State"] = "TX";
        $ParamsJson["City"] = "TX";
        $ParamsJson["Address1"] = "TX001";
        $ParamsJson["Address2"] = "";
        $ParamsJson["Contact"] = "13467987541";
        $ParamsJson["Email"] = "";
        $ParamsJson["Company"] = "";
        $ParamsJson["StockID"] = "15";
        $ParamsJson["Signature"] = "0";
        $ParamsJson["Insurance"] = "0";
        $ParamsJson["OrderDetail"]["CnName"] = "杯子";
        $ParamsJson["OrderDetail"]["EnName"] = "cup";
        $ParamsJson["OrderDetail"]["SKU"] = "cup";
        $ParamsJson["OrderDetail"]["Quantity"] = "1";
        $ParamsJson["OrderDetail"]["Weight"] = "1";
        $ParamsJson["OrderDetail"]["Length"] = "1";
        $ParamsJson["OrderDetail"]["Width"] = "1";
        $ParamsJson["OrderDetail"]["High"] = "1";
        $ParamsJson["OrderDetail"]["Price"] = "1";
        $ParamsJson["OrderDetail"]["HSCode"] = "";
        $ParamsJson["OrderDetail"]["Origin"] = "";
// halt($ParamsJson);
        $ParamsJson = (is_array($ParamsJson)) ? json_encode($ParamsJson, JSON_UNESCAPED_UNICODE) : $ParamsJson;
        $token = '3o4t3ILjmdn2b59zBNQUDzJJ/mYjz/cZlvwtTFb/oyY=';
        $url = 'http://120.79.79.121:8101/WebService/PublicService.asmx/CreateOrder';
        $data = array(
            'token'=>$token,
            'ParamsJson'=>$ParamsJson,
        );
        $data = http_build_query($data);
        $return = $this->posturl_whc($url,$data);
        halt($return);
        return $return;
    }
    
    /**
    * GetStockList
    * @param array params
    */
    public function GetStockList()
    {
        $token = '3o4t3ILjmdn2b59zBNQUDzJJ/mYjz/cZlvwtTFb/oyY=';
        $url = 'http://120.79.79.121:8101/WebService/PublicService.asmx/GetStockList';
        $data = array(
            'token'=>$token,
        );
        $data = http_build_query($data);
        $a = $this->posturl_whc($url,$data);
        halt($a);
    }
    /**
    * GetShipperService
    * @param array params
    */
    public function GetShipperService()
    {
        $token = '3o4t3ILjmdn2b59zBNQUDzJJ/mYjz/cZlvwtTFb/oyY=';
        $url = 'http://120.79.79.121:8101/WebService/PublicService.asmx/GetShipperService';
        $data = array(
            'token'=>$token,
        );
        $data = http_build_query($data);
        $a = $this->posturl_whc($url,$data);
        halt($a);
    }
    
    /**
 * get请求
 */
    function geturl($url)
    {
        $headerArray = array("Content-Type:application/json;", 'x-tts-access-token:' . $this->access_token);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    function posturl($url, $data = array())
    {
        $data = (is_array($data)) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
        $headerArray = array("Content-Type:application/json;", 'x-tts-access-token:' . $this->access_token);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    function posturl_whc($url, $data)
    {
        $headerArray = array("Content-Type:application/x-www-form-urlencoded;");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
